<template>
  <div class="container">
    <!--头部筛选 start-->
    <div class="flex-row justify-between p_b10">
      <div>
        <el-input size="small" v-model="params.filter" placeholder="搜索关键词..." class="m_r10 width200"></el-input>
        <el-button size="small" type="primary" icon="el-icon-search" @click="onPageChange(1)"></el-button>
        <el-button size="small" type="primary" @click="onPageChange(1)">刷新</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" @click="toggleEditorModal(true)" v-if="userInfo.role==='doctor'">开药
        </el-button>
      </div>
    </div>
    <!--头部筛选 end-->

    <!--列表数据 start-->
    <el-table :data="tableData" border size="mini">
      <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
      <el-table-column prop="doctorName" align="center" :min-width="100" label="开药医生"></el-table-column>
      <el-table-column prop="patientName" align="center" :min-width="100" label="患者"></el-table-column>
      <el-table-column prop="price" align="center" :min-width="100" label="价格"></el-table-column>
      <el-table-column prop="time" :min-width="200" label="药品">
        <template v-slot="{row}">
          <div v-for="(item,i) of row.mmsMedicineOrderList||[]" :key="i">
            {{ item.medicineName }}（{{ item.val }}{{ item.unit }}）
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" :min-width="180" align="center" label="开药时间"></el-table-column>
      <el-table-column prop="medicineDirection" align="center" :min-width="100" label="备注"></el-table-column>
    </el-table>
    <!--列表数据 end-->


    <!--分页组件 start-->
    <div class="pagination">
      <el-pagination
          background layout="total, prev, pager, next"
          :current-page="pageMeta.current_page"
          :page-size="pageMeta.limit" :total="pageMeta.total"
          @current-change="onPageChange"></el-pagination>
    </div>
    <!--分页组件 end-->

    <!--分类编辑、新增弹框 start-->
    <el-dialog
        v-model="formData.show"
        :title="formData.data.id>0?'编辑':'开药'"
        width="600px">
      <el-form
          ref="formRefName"
          :rules="rules"
          :model="formData.data" label-width="120px">
        <el-form-item label="患者">
          <el-select v-model="formData.data.patientId" placeholder="选择患者">
            <el-option
                v-for="(item,index) in patientLists"
                :key="`patient-${index}`"
                :label="item.name"
                :value="item.phone">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="疾病名称">
          <el-input v-model="formData.data.diseaseName" placeholder="疾病名称"></el-input>
        </el-form-item>
        <el-form-item label="用药时间">
          <div class="flex-row p_b5" v-for="(item,i) of useMedicineTimes" :key="i">
            <el-date-picker
                :disabledDate="disabledDate"
                v-model="useMedicineTimes[i]"
                type="datetime"
                placeholder="请选择用药时间">
            </el-date-picker>
            <el-button @click="onRemoveTime(i)" class="m_l5" v-if="i>0">-</el-button>
            <el-button @click="onAddTime" class="m_l5" v-if="i===useMedicineTimes.length-1">+</el-button>
          </div>
        </el-form-item>
        <el-form-item label="药品">
          <el-select
              multiple
              v-model="formData.data.medicineIds"
              placeholder="选择药品">
            <el-option
                v-for="(item,index) in medicineLists"
                :key="`medicine-${index}`"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="item.name" v-for="(item,i) of checkedMedicineLists" :key="i">
          <div class="flex-row">
            <el-input-number :min="1" v-model="item.val" placeholder="数量"></el-input-number>
            <el-input class="m_l5 flex" v-model="item.unit" style="width: 60px" placeholder="单位"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input
              type="textarea" :rows="4"
              show-word-limit
              :maxlength="200"
              v-model="formData.data.medicineDirection"
              placeholder="备注信息"></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleEditorModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onSubmit()">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!--分类编辑、新增弹框 end-->
  </div>


</template>

<script>
import {computed, defineComponent, reactive, ref, toRaw, watch} from "vue"
import {usePageMeta} from "../../hooks/usePageTableData";
import {deepClone, isEmpty} from "../../utils/helpers";
import Toast from "../../utils/Toast";
import Orders from "../../api/modules/Orders";
import {useStore} from "vuex";
import dayjs from "dayjs";
import Patient from "../../api/modules/Patient";
import Medicine from "../../api/modules/Medicine";

export default defineComponent({
  name: "Orders",
  data() {
    return {
      rules: {
        name: [
          {required: true, message: "请填写名称"}
        ],
        price: [
          {required: true, message: "请填写价格"},
          {type: 'number', min: 0, max: 99999, transform: v => Number(v) || '', message: "价格范围在0~99999之间"},
        ]
      },
    }
  },
  methods: {
    // 不可选择的时间
    disabledDate(date) {
      const nowDay = dayjs().startOf('day'); // 当天
      return dayjs(date).isBefore(nowDay); // 禁用小于当天的日期选择
    }
  },
  setup() {
    const store = useStore();
    const formRefName = ref(null);
    const pageHandle = usePageMeta(); // 分页相关数据
    const userInfo = computed(() => store.state.user.userInfo)
    const params = reactive({ // 筛选条件
      filter: "",
    });
    const tableData = ref([]); // 接口返回的数据列表

    onPageChange(1); // 初始化时直接请求一次分类列表
    initData();

    const patientLists = ref([]); // 患者列表
    const medicineLists = ref([]); // 药品列表

    // 初始化数据（获取所有患者信息、所有药品信息）
    function initData() {
      // 患者信息列表
      Patient.lists({
        index: 1,
        limit: 99999,
      }).then(res => {
        const data = res.data || {}
        patientLists.value = data.data || []
      }).catch(console.log)

      // 药品信息列表
      Medicine.lists({
        index: 1,
        limit: 99999,
      }).then(res => {
        const data = res.data || {}
        medicineLists.value = data.data || []
      }).catch(console.log)
    }


    /**
     * 获取订单列表数据
     * @param page page===undefined时表示刷新当前页面
     * @returns {Promise<void>}
     */
    async function onPageChange(page) {
      const pageMeta = deepClone(toRaw(pageHandle.pageMeta.value));
      if (page) {
        pageMeta.index = page;
      }
      try {
        const _params = {
          ...pageMeta, // 分页数据（当前页数，每页请求数量等）
          ...params, // 筛选参数（搜索条件等）
          doctorCode: store.state.user.userInfo.code, // 当前登录医生编号
        };

        const {data} = await Orders.lists(_params);
        tableData.value = data.data || data.list || [];
        // 请求到数据，更新公共的分页数据页码数
        pageHandle.updatePageMeta(pageMeta.index, data.count || data.total || 0);

      } catch (e) {
        console.log(e);
      }
    }

    const useMedicineTimes = ref([]);// 用药时间列表
    function onAddTime() { // 新增用药时间项
      useMedicineTimes.value.push("")
    }

    function onRemoveTime(index) { // 移除用药时间项
      useMedicineTimes.value.splice(index, 1)
    }

    const checkedMedicineLists = ref([]);// 当前选中的药品列表
    const formData = reactive({ // 新增编辑弹框的表单数据
      show: false, // 是否打开表单
      data: {
        id: 0, // id===0:新增操作，id>0:编辑操作
        patientId: '', // 选择的患者id
        diseaseName: '', // 疾病名称
        medicineIds: [], // 选择的药品id列表
        medicineDirection: "", // 医生备注
      }
    });

    const _formData = deepClone(toRaw(formData)); // 拷贝一份原始的表单数据（用于还原数据使用）
    // 监听药品选择的变化
    watch(() => formData.data.medicineIds, (val, oldVal) => {

      checkedMedicineLists.value = medicineLists.value.filter(v => { // 筛选出选中的药品
        return val.includes(v.id);
      }).map(item => { // 设置默认选中的数量和单位
        item.val = 1;
        item.unit = '盒';
        return item;
      });
    })

    // 开药提交
    async function onSubmit() {
      // 拷贝一份表单数据
      const _formData = deepClone(toRaw(formData)).data;
      try {
        if (isEmpty(_formData.patientId)) {
          throw new Error('请选择患者')
        }
        if (isEmpty(_formData.diseaseName)) {
          throw new Error('请填写疾病名称')
        }

        // 拷贝一份选择的药品数据
        const _checks = deepClone(toRaw(checkedMedicineLists.value));
        if (isEmpty(_formData.medicineIds) || isEmpty(_checks)) {
          throw new Error('请选择药品')
        }

        for (let c of _checks) {
          if (c.val <= 0) {
            throw new Error(`药品【${c.name}】必须填写数量`)
          }
          if (isEmpty(c.unit)) {
            throw new Error(`药品【${c.name}】必须填写单位`)
          }
        }
        // 订单中保留的药品信息
        const medicineAndNumList = _checks.map(v => {
          return {
            medicineCode: String(v.code), // 药品code
            val: v.val, // 选择药品数量
            unit: v.unit, // 药品单位
          }
        })
        // 用药时间列表
        const times = useMedicineTimes.value.filter(v => {
          return !isEmpty(v); // 仅保留不为空的数据
        }).map(v => {
          // 格式化时间格式
          return dayjs(v).format("YYYY-MM-DD HH:mm:ss")
        });
        const res = await Orders.create({
          doctorCode: userInfo.value.code, // 医生编码
          patientPhone: _formData.patientId, // 患者id、患者手机号
          medicineDirection: _formData.medicineDirection, // 医生备注
          diseaseName: _formData.diseaseName, // 疾病名称
          treatTime: dayjs().format("YYYY-MM-DD HH:mm:ss"), // 就趁时间
          medicineAndNumList: JSON.stringify(medicineAndNumList), // 订单中保留的药品信息
          useMedicineTimes: JSON.stringify(times), // 用药时间列表
        });
        onPageChange(1); // 成功则刷新页面 （新增操作 将请求第一页的数据）
        Toast.success('开药成功');
        toggleEditorModal(false); //关闭新增、编辑弹框
      } catch (e) { // 新增、编辑操作提交错误或者失败
        Toast.error(e.message);
      }
    }

    /**
     * 打开、关闭开药弹框
     * @param show true :打开 false 关闭
     * @param data
     */
    function toggleEditorModal(show, data = {}) {
      formData.show = show;
      useMedicineTimes.value = data.useMedicineTimes || [""];
      formData.data = Object.assign(
          {}, // Object.assign 会填充到第一项的参数，使用一个{}空对象 防止数据污染
          _formData.data, // 备份的原始数据
          data, // 编辑时该数据不为空 可填充 覆盖 原始数据_formData.data
      );
      if (formRefName.value) {
        formRefName.value.resetFields(); // 清除表单的验证信息
      }

    }


    return {
      ...pageHandle,
      userInfo,
      onSubmit,
      onAddTime,
      onRemoveTime,
      useMedicineTimes,
      patientLists,
      medicineLists,
      checkedMedicineLists,
      toggleEditorModal,
      params,
      formRefName,
      tableData,
      formData,
      onPageChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.car-image {
  width: 60px;
  height: 40px;
}

.user-cover {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
</style>
